package stancel.peter.smartsilencer.activities;

import java.util.List;

import stancel.peter.smartsilencer.Event;
import stancel.peter.smartsilencer.R;
import stancel.peter.smartsilencer.SmartSilencer;
import stancel.peter.smartsilencer.background.CheckingService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * Trieda na vytvaranie a menenie casovych udalosti.
 * 
 * @author Peter Stancel
 */
public class TimeActivity extends Activity implements OnClickListener {

	private SmartSilencer smartSilencer;
	private List<Event> list;

	private EditText editTextName;
	private RadioButton radioButtonVibration;
	private RadioButton radioButtonSilence;
	private CheckBox airplane;
	private Button button;
	private TimePicker timePickerStart;
	private TimePicker timePickerEnd;
	private CheckBox monday;
	private CheckBox tuesday;
	private CheckBox wednesday;
	private CheckBox thursday;
	private CheckBox friday;
	private CheckBox saturday;
	private CheckBox sunday;
	private CheckBox onetime;
	// private String oldName;

	private Event event;
	private int eventIndex;

	private boolean[] days = new boolean[7];

	private static final int ALERT_NAME_ID = 0;
	private static final int ALERT_CHECKBOX_ID = 1;

	/**
	 * Vola sa pri vytvarani tejto aktivity.
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.time);

		editTextName = (EditText) findViewById(R.id.edit_name);
		radioButtonVibration = (RadioButton) findViewById(R.id.radio_vibration);
		radioButtonSilence = (RadioButton) findViewById(R.id.radio_silence);
		airplane = (CheckBox) findViewById(R.id.checkbox_airplane);

		monday = (CheckBox) findViewById(R.id.chboxMonday);
		tuesday = (CheckBox) findViewById(R.id.chboxTuesday);
		wednesday = (CheckBox) findViewById(R.id.chboxWednesday);
		thursday = (CheckBox) findViewById(R.id.chboxThursday);
		friday = (CheckBox) findViewById(R.id.chboxFriday);
		saturday = (CheckBox) findViewById(R.id.chboxSaturday);
		sunday = (CheckBox) findViewById(R.id.chboxSunday);
		onetime = (CheckBox) findViewById(R.id.checkbox_onetime);

		button = (Button) findViewById(R.id.button_create);
		button.setOnClickListener(this);

		timePickerStart = (TimePicker) findViewById(R.id.timepicker_start);
		timePickerEnd = (TimePicker) findViewById(R.id.timepicker_end);
		timePickerStart.setIs24HourView(true);
		timePickerEnd.setIs24HourView(true);

		smartSilencer = (SmartSilencer) getApplication();
		list = smartSilencer.loadFromFile();

		eventIndex = getIntent().getIntExtra("smartsilencer_index", -1);
		if (eventIndex != -1 && !list.isEmpty()) {
			event = (Event) list.get(eventIndex);

			button.setText(R.string.modify_event);
			editTextName.setText(event.getName());
			// oldName = event.getName();
			radioButtonSilence.setChecked(event.isSilence());
			radioButtonVibration.setChecked(event.isVibration());
			airplane.setChecked(event.isAirplaneMode());
			onetime.setChecked(event.isOnetime());

			days = event.getDays();
			sunday.setChecked(days[0]);
			monday.setChecked(days[1]);
			tuesday.setChecked(days[2]);
			wednesday.setChecked(days[3]);
			thursday.setChecked(days[4]);
			friday.setChecked(days[5]);
			saturday.setChecked(days[6]);

			timePickerStart.setCurrentHour(event.getDateStart() / 100);
			timePickerStart.setCurrentMinute(event.getDateStart() % 100);
			timePickerEnd.setCurrentHour(event.getDateEnd() / 100);
			timePickerEnd.setCurrentMinute(event.getDateEnd() % 100);
		}
	}

	/**
	 * Po stlaceni tlacidla overi udaje a ak su spravne, vytvori udalost.
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button_create:
			String name = editTextName.getText().toString().trim();
			if (!name.equals("")) {
				if (!checkName(name) || eventIndex != -1) {
					if (isDayChecked()) {
						int dateStart = timePickerStart.getCurrentHour() * 100 + timePickerStart.getCurrentMinute();
						int dateEnd = timePickerEnd.getCurrentHour() * 100 + timePickerEnd.getCurrentMinute();

						boolean nextDay;
						if (dateStart >= dateEnd) {
							nextDay = true;
						} else {
							nextDay = false;
						}

						Log.i("TIMEACTIVITY", dateStart + "    " + dateEnd);

						if (eventIndex != -1) {
							event.setName(name);
							event.setVibration(radioButtonVibration.isChecked());
							event.setSilence(radioButtonSilence.isChecked());
							event.setAirplaneMode(airplane.isChecked());
							event.setDateStart(dateStart);
							event.setDateEnd(dateEnd);
							event.setNextDay(nextDay);
							event.setDays(days);
							event.setOnetime(onetime.isChecked());
							Toast.makeText(TimeActivity.this, R.string.event_modified, Toast.LENGTH_SHORT).show();
						} else {
							Event event = new Event(name, radioButtonVibration.isChecked(), radioButtonSilence.isChecked(),
									airplane.isChecked(), onetime.isChecked(), dateStart, dateEnd, days, nextDay);
							list.add(event);
							Toast.makeText(TimeActivity.this, R.string.event_created, Toast.LENGTH_SHORT).show();
						}
						smartSilencer.saveListToFile(list);
						startService(new Intent(this, CheckingService.class));
						finish();
					} else
						showDialog(ALERT_CHECKBOX_ID);
				} else
					showDialog(ALERT_NAME_ID);
			} else
				showDialog(ALERT_NAME_ID);
			break;
		}
	}

	/**
	 * Vytvata dialog s chybovim hlasenim.
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		super.onCreateDialog(id);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.wrong_inputs).setCancelable(true)
				.setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});

		switch (id) {
		case ALERT_NAME_ID:
			return builder.setMessage(R.string.event_name_miss).create();
		case ALERT_CHECKBOX_ID:
			return builder.setMessage(R.string.check_days).create();
		default:
			return null;
		}
	}

	/**
	 * Zistuje, ci bol zaskrtnuty aspon jeden den.
	 * 
	 * @return true ak bol, inak false
	 */
	private boolean isDayChecked() {
		days[0] = sunday.isChecked();
		days[1] = monday.isChecked();
		days[2] = tuesday.isChecked();
		days[3] = wednesday.isChecked();
		days[4] = thursday.isChecked();
		days[5] = friday.isChecked();
		days[6] = saturday.isChecked();

		for (boolean day : days) {
			if (day) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Overi, ci uz existuje udalost s rovnakym menom a rovnakym typom.
	 */
	public boolean checkName(String name) {
		for (Event event : list) {
			if (event.getName().equals(name)) {
				return true;
			}
		}
		return false;
	}
}